package cn.itcast.goods.category.dao;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.category.domain.Cate;
import cn.itcast.goods.user.DBConn.DbConn;
import cn.itcast.jdbc.TxQueryRunner;
import com.mysql.jdbc.Connection;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CateDao {
    private QueryRunner queryRunner=new TxQueryRunner();
    private Connection conn=null;
    public List<Cate> queryAll()
    {

        String sql="select * from t_category where pid is null";
        conn= DbConn.getConnection();
        List<Map<String,Object>> list=new ArrayList<>();
        List<Cate> parents=null;
        try{
            list=queryRunner.query(conn,sql,new MapListHandler());
            parents=toCateList(list);
            for (Cate parent:parents)
            {
                List<Cate> child=findChildByParent(parent.getCid());
                parent.setChild(child);
            }
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        return parents;
    }

    private List<Cate> findChildByParent(String pid) {
        String sql="select * from t_category where pid=?";
        Object[] param={pid};
        List<Map<String,Object>> list =new ArrayList<>();
        try{
             list=queryRunner.query(conn,sql,new MapListHandler(),param);
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        return toCateList(list);
    }

    public Cate toCate(Map<String,Object> map)
    {
            Cate cate= CommonUtils.toBean(map,Cate.class);
            String pid=(String)map.get("pic");
            if (pid!=null)
            {
                Cate parent=new Cate();
                parent.setCid(pid);
                cate.setParent(parent);
            }
            return cate;
    }
    public List<Cate> toCateList(List<Map<String,Object>> mapList)
    {
        List<Cate> list=new ArrayList<>();
        for (Map map:mapList)
        {
            Cate cate=toCate(map);
            list.add(cate);
        }
        return list;
    }
}
